import member from '@/api/member'
import common from './common'

const state = {
    memberNum: {
        requestSend: false,
        data: []
    },
    members: {
        requestSend: false,
        noData: false,
        ajaxing: false,
        data: []
    },
    upper: {
        requestSend: false,
        ajaxing: false,
        data: {}
    },
    membershipGoods: {
        requestSend: false,
        data: {}
    }
}

const getters = {
    memberNum: state => state.memberNum.data,
    members: state => state.members.data,
    membersAjaxing: state => state.members.ajaxing,
    upper: state => state.upper.data,
    upperAjaxing: state => state.upper.ajaxing,
    membershipGoods: state => state.membershipGoods.data
}

const actions = {
    async getMembers ({state, commit}, rank) {
        // 这里还是应该每次都进行请求的 因为存在有人扫码后 被扫码者立即查看下级的情况
        commit('ajaxing', {name: 'members', ajaxing: true})
        const {data, success} = await member.getMembers(rank)
        commit('ajaxing', {name: 'members', ajaxing: false})
        commit('requestSend', 'members')
        commit('memberNum', data.number)
        commit('members', data.first)
    },
    async getUpper ({state, commit}) {
        if (state.upper.requestSend) return state.upper.data
        const {data, success} = await member.getUpper()
        commit('requestSend', 'upper')
        commit('upper', data)
    },
    async changeUpper ({state, commit}, code) {
        commit('ajaxing', {name: 'upper', ajaxing: true})
        const {data, success, msg} = await member.changeUpper(code)
        commit('ajaxing', {name: 'upper', ajaxing: false})
        if (success) commit('upper', data)
        return {success, msg}
    },
    async getMembershipGoods ({state, commit}) {
        if (state.membershipGoods.requestSend) {
            return {
                data: state.membershipGoods.data,
                success: true
            }
        }
        const {data, success} = await member.getMembershipGoods()
        if (success) {
            commit('requestSend', 'membershipGoods')
            commit('membershipGoods', data)
        }
        return {data, success}
    },
    async askMembership ({commit}, no) {
        const { success, msg } = await member.askMembership(no)
        if (success) commit('user/changeUserLevel', 2, {root: true})
        return {success, msg}
    }
}

const mutations = {
    memberNum (state, nums) {
        state.memberNum.data = nums
    },
    members (state, members) {
        state.members.data = members
        if (!members.length) state.members.noData = true
    },
    clearMembers (state, members) {
        state.members.data = []
    },
    upper (state, upper) {
        state.upper.data = upper
    },
    membershipGoods (state, goods) {
        state.membershipGoods.data = goods
    },
    requestSend: common.requestSend,
    ajaxing: common.ajaxing
}

export default {
    state,
    getters,
    actions,
    mutations,
    namespaced: true
}
